<template>
	<view class="share_main">
		<!-- 分享弹框 start -->
		<view class="share_model" v-if="share_model" @touchmove.stop.prevent="moveHandle">
			<view class="share_model_list">
				<!-- #ifdef H5 -->
				<view class="share_model_pre" @tap.stop="sldShareBrower" v-if="isWeiXinBrower">
					<image :src="imgUrl+'goods_detail/wx_share.png'" mode="aspectFit"></image>
					<text>{{$L('微信好友')}}</text>
				</view>
				<view class="share_model_pre" @tap.stop="sldShareBrower" v-if="isWeiXinBrower">
					<image :src="imgUrl+'goods_detail/wechat_moments.png'" mode="aspectFit"></image>
					<text>{{$L('微信朋友圈')}}</text>
				</view>
				<!-- #endif -->
				<!-- #ifdef MP-WEIXIN -->
				<button open-type="share" class="share_model_pre" @click="closeShareModel">
					<image :src="imgUrl+'goods_detail/wx_share.png'" mode="aspectFit"></image>
					<text>{{$L('微信好友')}}</text>
				</button>
				<!-- #endif -->
				<!-- #ifdef APP-PLUS -->
				<view class="share_model_pre" @tap.stop="sldShare(0,'WXSceneSession')">
					<image :src="imgUrl+'goods_detail/wx_share.png'" mode="aspectFit"></image>
					<text>{{$L('微信好友')}}</text>
				</view>
				<view class="share_model_pre" @tap.stop="sldShare(0,'WXSenceTimeline')">
					<image :src="imgUrl+'goods_detail/wechat_moments.png'" mode="aspectFit"></image>
					<text>{{$L('微信朋友圈')}}</text>
				</view>
				<!-- #endif -->
				<view class="share_model_pre" v-if="type!='shop'">
					<image :src="imgUrl+'goods_detail/poster.png'" mode="aspectFit" @click="getPoster"></image>
					<text>{{$L('生成海报')}}</text>
				</view>
			</view>
			<view class="share_model_close" @click="closeShareModel">
				<image :src="imgUrl+'goods_detail/share_close.png'" mode="aspectFit"></image>
			</view>
		</view>
		<!-- 分享弹框 end -->



		<!-- 生成海报  start-->
		<view class="poster" v-if="poster" @touchmove.stop.prevent="moveHandle">
			<!-- 分享海报弹框 start -->
			<view class="share_model" :class="{poster_share_model:poster}">
				<!-- #ifndef MP-WEIXIN -->
				<image :src="sharePoster" mode="aspectFit" class="poster_image" @longtap.stop="downloadPoster"></image>
				<!-- #endif -->
				<!-- #ifdef MP-WEIXIN -->
				<image :src="sharePoster" mode="aspectFit" class="poster_image" show-menu-by-longpress="true" @tap="wxPreview">
				</image>
				<!-- #endif -->
				<view class="share_model_list">
					<!-- #ifdef MP-WEIXIN -->
					<view class="share_model_pre" @tap.stop="downloadPoster">
						<image :src="imgUrl+'goods_detail/poster.png'" mode="aspectFit"></image>
						<text>{{$L('下载海报')}}</text>
					</view>
					<!-- #endif -->
					<!-- #ifdef APP-PLUS -->
					<view class="share_model_pre" @tap.stop="saveImgAPP">
						<image :src="imgUrl+'goods_detail/poster.png'" mode="aspectFit"></image>
						<text>{{$L('保存海报')}}</text>
					</view>
					<view class="share_model_pre" @tap.stop="sldShare(2,'WXSceneSession')">
						<image :src="imgUrl+'goods_detail/wx_share.png'" mode="aspectFit"></image>
						<text>{{$L('微信好友')}}</text>
					</view>
					<view class="share_model_pre" @tap.stop="sldShare(2,'WXSenceTimeline')">
						<image :src="imgUrl+'goods_detail/wechat_moments.png'" mode="aspectFit"></image>
						<text>{{$L('微信朋友圈')}}</text>
					</view>
					<!-- #endif -->
				</view>
				<!-- #ifndef H5 -->
				<view class="share_model_close" @click="closeShareModel">
					<image :src="imgUrl+'goods_detail/share_close.png'" mode="aspectFit"></image>
				</view>
				<!-- #endif -->
				<!-- #ifdef H5 -->
				<image :src="imgUrl+'goods_detail/poster_share.png'" mode="aspectFit" class="poster_share_img"
					@longtap.stop="downloadPoster"></image>
				<image :src="imgUrl+'goods_detail/poster_share_close.png'" mode="aspectFit" class="poster_share_close"
					@click.stop="closePoster"></image>
				<!-- #endif -->
			</view>
			<!-- 分享海报弹框 end -->

		</view>
		<!-- 生成海报  end-->
		<!-- 微信浏览器分享提示  start-->
		<view class="wx_brower_share_mask" v-if="showWeiXinBrowerTip">
			<view class="wx_brower_share_top_wrap">
				<image :src="imgUrl+'wx_share_tip.png'" mode="widthFix" @tap="closeShareModel"
					class="wx_brower_share_img"></image>
			</view>
		</view>
		<!-- 微信浏览器分享提示  end-->
	</view>
</template>

<script>
	import {
		weBtoa
	} from '@/utils/base.js'
	export default {
		components: {},
		props: ['goodsData', 'type'],
		data() {
			return {
				dialogTitle: this.$L('温馨提示!'),
				dialogCon: this.$L('您需要先登录哦～'),
				imgUrl: getApp().globalData.imgUrl,
				share_model: false, //分享弹框
				shareList: [],
				poster: false, //生成海报,
				showWeiXinBrowerTip: false, //微信浏览器分享的提示操作,
				isWeiXinBrower: false, //是否微信浏览器,
				productId: 0,
				data: {},
				poster1: null,
				source: 0,
				sharePoster: ''
			}
		},
		mounted() {
			//#ifdef MP-TOUTIAO
			this.source = 1;
			//#endif
			//#ifdef MP-ALIPAY
			this.source = 2;
			//#endif
			// #ifdef MP-BAIDU
			this.source = 3;
			// #endif
			//#ifdef MP-WEIXIN
			this.source = 4;
			//#endif
			if (this.type == 'goods' && JSON.stringify(this.goodsData) != '{}') {
				this.getLink(this.goodsData)
				this.getTsPoster()
			}
			this.isWeiXinBrower = this.$isWeiXinBrower()
		},
		watch: {
			goodsData: {
				handler(newV, oldV) {
					if (newV != oldV && JSON.stringify(newV) != '{}' && this.type == 'goods') {
						this.getLink(newV)
						this.getTsPoster()
					}
				},
				deep: true
			},
			sharePoster: {
				handler(nv, ov) {
					this.poster1 = nv
				},
				deep: true
			}
		},
		methods: {
			//浏览器分享
			sldShareBrower() {
				this.showWeiXinBrowerTip = true;
				this.share_model = false;
				this.$weiXinBrowerShare(1, {
					title: this.goodsData.goodsName,
					desc: this.goodsData.goodsBrief,
					link: this.goodsData.shareLink,
					imgUrl: this.goodsData.goodsImage ? this.goodsData.goodsImage : this.goodsData.productImage,
				});
			},
			//获取海报
			getPoster() {
				this.share_model = false;
				this.showWeiXinBrowerTip = false;
				this.poster = true;
			},

			//关闭分享弹框
			closeShareModel() {
				this.share_model = false;
				this.showWeiXinBrowerTip = false;
				this.poster = false;
			},

			//分享 type：分享类型 0 图文 2图片，scene 场景 WXSceneSession：分享朋友  WXSenceTimeline：分享朋友圈
			sldShare: function(type, scene) {
				let shareData = {};
				let {
					goodsData,
					sharePoster
				} = this;
				if (type == 0) {
					shareData.href = goodsData.shareLink;
					shareData.title = goodsData.goodsName;
					shareData.summary = goodsData.goodsBrief;
					shareData.imageUrl = goodsData.shareImage ? goodsData.shareImage : goodsData.goodsImage;
				} else if (type == 2) {
					shareData.imageUrl = sharePoster;
				}
				this.$weiXinAppShare(type, scene, shareData);
				this.closeShareModel(); //关闭分享
			},

			getLink(data) {
				this.$request({
					url: 'v3/spreader/front/spreaderGoods/share',
					data: {
						productId: data.defaultProduct ? data.defaultProduct.productId : data.productId
					}
				}).then(res => {
					if (res.state == 200) {
						this.goodsData.shareLink = res.data.shareLink
						this.$emit('getLink', res.data.shareLink)
					}
				})
			},

			wxPreview() {
				wx.previewImage({
					urls: [this.sharePoster]
				})
			},



			// 获取分享海报
			getTsPoster() {
				this.$request({
					url: 'v3/spreader/front/spreader/share/sharePosters',
					data: {
						productId: this.goodsData.defaultProduct ? this.goodsData.defaultProduct.productId : this
							.goodsData.productId,
						source: this.source
					},
					responseType: 'arraybuffer',
				}).then(res => {
					// #ifdef H5
					this.sharePoster = 'data:image/png;base64,' + btoa(new Uint8Array(res).reduce((data, byte) =>
						data + String.fromCharCode(byte), ''))
					// #endif
					//#ifdef MP-WEIXIN
					this.sharePoster = 'data:image/png;base64,' + weBtoa(new Uint8Array(res).reduce((data, byte) =>
						data + String.fromCharCode(byte), ''))
					// #endif
					// #ifdef APP-PLUS
					this.sharePoster = 'data:image/png;base64,' + weBtoa(new Uint8Array(res).reduce((data, byte) =>
						data + String.fromCharCode(byte), '')).replace(/[\r\n]/g, "");
					// #endif
				})
			},

			downloadPoster() {
				let _this = this
				uni.getSetting({
					success(res_down) {
						if (!res_down.authSetting['scope.writePhotosAlbum']) {
							uni.showModal({
								title: _this.$L('提示'),
								content: _this.$L('您好,需要开启相册权限'),
								showCancel: false,
								success(res) {
									if (res.confirm) {
										uni.authorize({
											scope: 'scope.writePhotosAlbum',
											success() {
												// 用户已经同意,后续调用时不会弹窗询问
												_this.saveHb();
											},
											fail() {
												//拒绝授权
												uni.showToast({
													title: _this.$L('抱歉，没有授权无法下载海报'),
													icon: 'none'
												});
											}

										});
									}
								}

							});
						} else {
							_this.saveHb();
						}
					}

				});
				//#ifdef H5
				//阻止浏览器默认行为 
				document.oncontextmenu = function(e) {
					e.preventDefault()
				}
				//#endif
			},

			/**
			 * 保存图片
			 */
			saveHb(img) {
				let code = parseInt(Math.random() * 10000)
				let _this = this;
				let {
					sharePoster
				} = this;
				let base64 = sharePoster.replace(/^data:image\/\w+;base64,/, ""); //去掉data:image/png;base64,
				let filePath = wx.env.USER_DATA_PATH + `/image-${code}.png`;
				uni.getFileSystemManager().writeFile({
					filePath: filePath, //创建一个临时文件名
					data: base64, //写入的文本或二进制数据
					encoding: 'base64', //写入当前文件的字符编码
					success: res => {
						uni.saveImageToPhotosAlbum({
							filePath: filePath,
							success: function(res2) {
								uni.showToast({
									title: _this.$L('已保存到本地'),
									icon: 'success',
									duration: 2000
								})
							},
						})
					},
				})
			},
			
			//APP端保存图片的方法
			saveImgAPP() {
				let _this = this;
				let base64 = this.sharePoster;
				const bitmap = new plus.nativeObj.Bitmap("test");
				bitmap.loadBase64Data(base64, function() {
					const url = "_doc/" + new Date().getTime() + ".png"; // url为时间戳命名方式
					
					bitmap.save(url, {
						overwrite: true, // 是否覆盖
						// quality: 'quality'  // 图片清晰度
					}, (i) => {
						uni.saveImageToPhotosAlbum({
							filePath: url,
							success: function() {
								uni.showToast({
									title: _this.$L('图片保存成功'),
									icon: 'none'
								})
								bitmap.clear()
							}
						});
					}, (e) => {
						uni.showToast({
							title: _this.$L('图片保存失败'),
							icon: 'none'
						})
						bitmap.clear()
					});
				}, (e) => {
					uni.showToast({
						title: _this.$L('图片保存失败'),
						icon: 'none'
					})
					bitmap.clear()
				});
			},


			//关闭海报
			closePoster() {
				this.poster = false;
			},
		}
	}
</script>

<style lang="scss">
	.share_main {
		z-index: 99999999;
	}

	.share_model {
		width: 752rpx;
		height: 100%;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		margin: 0 auto;
		background: rgba(0, 0, 0, 0.6);
		z-index: 99999999;
	}



	.share_model_list {
		display: flex;
		justify-content: space-around;
		padding: 0 50rpx;
		box-sizing: border-box;
		position: fixed;
		bottom: 150rpx;
		/* #ifdef MP-WEIXIN */
		bottom: 136rpx;
		/* #endif */
		z-index: 110;
		width: 750rpx;

		.share_model_pre {
			display: flex;
			flex-direction: column;
			align-items: center;
			background: transparent;
			border-radius: 0;
			height: auto;
			line-height: auto;

			&::after {
				border-width: 0;
			}

			image {
				width: 105rpx;
				height: 105rpx;
			}

			text {
				font-size: 24rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 36rpx;
				margin-top: 30rpx;
			}
		}
	}

	.share_model_close {
		width: 46rpx;
		height: 46rpx;
		bottom: 60rpx;
		position: fixed;
		z-index: 110;
		left: 0;
		right: 0;
		margin: 0 auto;

		image {
			width: 46rpx;
			height: 46rpx;
		}
	}

	button {
		padding: 0;
		margin: 0;
	}

	.poster {
		width: 752rpx;
		height: 100%;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		margin: 0 auto;
		background: rgba(0, 0, 0, 0.6);
		z-index: 99999999;

		.poster_image {
			width: 541rpx;
			height: 837rpx;
			background: #FFFFFF;
			border-radius: 20rpx;
			position: absolute;
			left: 105rpx;
			/* #ifdef H5 */
			bottom: 360rpx;
			/* #endif */
			/* #ifndef H5 */
			bottom: 380rpx;
			/* #endif */
			/* #ifdef MP-WEIXIN */
			bottom: 330rpx;
			/* #endif */
		}

		.poster_share_img {
			width: 390rpx;
			height: 90rpx;
			/* left: 179rpx; */
			position: absolute;
			bottom: 177rpx;
			margin: 72rpx 0 22rpx;
		}

		.poster_share_close {
			width: 49rpx;
			height: 49rpx;
			position: absolute;
			/* left: 351rpx; */
			bottom: 105rpx;
		}

		/* #ifdef H5 */
		.poster_share_model {
			width: 750rpx;
			height: 100%;
			position: fixed;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			.poster_image {
				width: 541rpx;
				height: 837rpx;
				background: #FFFFFF;
				border-radius: 20rpx;
			}

			.poster_share_img {
				width: 390rpx;
				height: 90rpx;
				margin: 72rpx 0 22rpx;
			}

			.poster_share_close {
				width: 49rpx;
				height: 49rpx;
			}
		}

		/* #endif */
	}
</style>
